using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using DealerPlatform.Web.Models;
using Microsoft.IdentityModel.Tokens;

namespace DealerPlatform.Common.TokenModule
{
    public static class TokenHelper
    {
        public static string CreateToken(JwtTokenModel jwtToken)
        {
            var claims = new []{
                new Claim("Id", jwtToken.Id),
                new Claim("CustomerNo", jwtToken.CustomerNo),
                new Claim("CustomerName", jwtToken.CustomerName),
            };
            //生成密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtToken.Security));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: jwtToken.Issuer,
                audience: jwtToken.Audience,
                expires: DateTime.Now.AddMinutes(jwtToken.Expires),
                signingCredentials: creds,
                claims: claims
            );

            var accessToken = new JwtSecurityTokenHandler().WriteToken(token);
            return accessToken;
        }
        
        public static string CreateToken2(JwtTokenModel jwtToken, Dictionary<string, string> claimsDic)
        {
            List<Claim> claims = new List<Claim>();
            foreach(var claim in claimsDic.Keys)
            {
                claims.Add(new Claim(claim,claimsDic[claim]));
            }
            //生成密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtToken.Security));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: jwtToken.Issuer,
                audience: jwtToken.Audience,
                expires: DateTime.Now.AddMinutes(jwtToken.Expires),
                signingCredentials: creds,
                claims: claims
            );

            var accessToken = new JwtSecurityTokenHandler().WriteToken(token);
            return accessToken;
        }
    }
}